package org.hypirinha.utils.html2hypirinha;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import static org.hypirinha.html.AttributeFactory.*;
import static org.hypirinha.html.ElementFactory.*;
import org.hypirinha.html.elements.*;
import org.hypirinha.html.output.PrintAdapter;

import javax.servlet.http.*;

@SuppressWarnings("serial")
public class html2hypirinhaServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		
		Html html = html();
		String title = "HTML to Hypirinha Converter";
		Head head = html.head();
		head.title().text(title);
		head.link(href("google-code-prettify/prettify.css"), type("text/css"), rel("stylesheet"));
		head.script(type("text/javascript"), src("google-code-prettify/prettify.js"));
		Body body = html.body(onload("prettyPrint()"));
		body.h1().a(href("/html2hypirinha")).text(title);
		
        String urlParameter = req.getParameter("url");
        if (urlParameter == null) {
        	Form form = body.form(method("get"), action("html2hypirinha"));
        	form.p().text("Please enter a URL");
        	form.p().input(name("url"), type("text"));
        	form.p().input(type("submit"));
        } else {
			URL url = new URL(urlParameter);
	        InputStream inputStream = (InputStream) url.getContent();
        	String sourceCode = new BuilderClassGenerator().generate(new Cleaner().clean(inputStream));
        	
			P paragraph = body.p();
			paragraph.text("Java code below is intended to generate content matching ");
			paragraph.a(href(urlParameter)).text(urlParameter);
			paragraph.text(" using the HTML generator library ");
			paragraph.a(href("http://code.google.com/p/hypirinha/")).text("Hypirinha");
			body.pre(classs("prettyprint")).text(sourceCode);
        }
        
		resp.setContentType("text/html");
		new PrintAdapter().print(html, resp.getWriter());
	}
}
